package com.hudongwx.godoffood.activity.home_activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;

@ContentView(R.layout.activity_search_result)
public class SearchResultActivity extends AppCompatActivity {
    private String TAG = "SearchResultActivity";
    @ViewInject(R.id.search_result_recycler)
    RecyclerView recyclerView;//用于显示搜索成功时的商品
    @ViewInject(R.id.search_result_recycler2)
    RecyclerView recyclerView2;//用于显示搜索失败时的推荐商品
    @ViewInject(R.id.search_result_input)
    EditText input;

    private JSONArray data2;
    private String inputContent;
    private int state;
    private String key;
    private SharedPreferences sharedPreferences;
    @ViewInject(R.id.search_result_fail)
    LinearLayout fail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);


        //设置recyclerview的item之间的间距
        recyclerView.addItemDecoration(new SpaceItemDecoration(30));
        //设置recyclerview的item之间的间距
        recyclerView2.addItemDecoration(new SpaceItemDecoration(10));


        //SharedPreferences对应了一个xml的文件，用来存放数据
        sharedPreferences = getSharedPreferences("search", MODE_PRIVATE);
        Log.i(TAG, "onCreate: 搜索++");
        //获取输入框内容并设置进去
        inputContent = getIntent().getStringExtra("input");
        input.setText(inputContent);


        String data = getIntent().getStringExtra("data");
        state = getIntent().getIntExtra("state",0);
        try {
            //将字符串转换为JSONArray
            data2 = new JSONArray(data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //判断搜索结果
        judgeResult(state);


        input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //关闭软键盘
                InputMethodManager imm = (InputMethodManager) SearchResultActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(input.getWindowToken() , 0);

                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    //获取输入内容
                    inputContent = v.getText()+"";
                    try {
                        //将搜索内容进行url编码
                        String inputContent2 =  java.net.URLEncoder.encode(inputContent,"utf-8");
                        Log.i(TAG, "onEditorAction: "+inputContent2);
                        loadSearch(inputContent2);

                        key = System.currentTimeMillis()+"";
                        //获取到了一个编辑器
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //添加数据，这里存放在内存中，还没有持久化：没有把数据写入到磁盘
                        editor.putString(key,inputContent);
                        //写入到磁盘
                        editor.commit();

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }
        });

    }

    /**
     * 判断搜索结果
     * @param state
     */
    public void judgeResult(int state){
        //搜索成功
        if (state == 1){
            recyclerView.setVisibility(View.VISIBLE);
            fail.setVisibility(View.GONE);

            GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
            recyclerView.setLayoutManager(gridLayoutManager);
            recyclerView.setAdapter(new MyRecyclerAdapter(data2));

        }else {//搜索失败
            recyclerView.setVisibility(View.GONE);
            fail.setVisibility(View.VISIBLE);

            GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
            recyclerView2.setLayoutManager(gridLayoutManager);
            recyclerView2.setAdapter(new MyRecyclerAdapter(data2));
        }
    }

    class MyRecyclerAdapter extends RecyclerView.Adapter<ResultViewHolder>{
        JSONArray data;

        public MyRecyclerAdapter(JSONArray data) {
            this.data = data;
        }

        @Override
        public ResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(SearchResultActivity.this).inflate(R.layout.search_result_item, null);
            return new ResultViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ResultViewHolder holder, int position) {
            try {
                JSONObject item = data.getJSONObject(position);
                x.image().bind(holder.imageView,item.getString("ImgUrl"));
                holder.textView1.setText(item.getString("ProductName"));
                holder.textView2.setText("￥"+item.getString("UnitPrice")+".00");

                SearchItemClickListener listener = new SearchItemClickListener();
                JSONArray relevantSpecs = item.getJSONArray("RelevantSpecs");
                int len = relevantSpecs.length();
                String[] productIDList = new String[len];//用于存放商品ID
                for (int i = 0; i < len; i++) {
                    productIDList[i] = relevantSpecs.getJSONObject(i).getString("ProductID");
                }
                holder.imageView.setTag(productIDList);
                holder.imageView.setOnClickListener(listener);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public int getItemCount() {
            return data.length();
        }
    }

    class ResultViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView textView1,textView2;

        public ResultViewHolder(View itemView) {
            super(itemView);
            this.imageView = (ImageView) itemView.findViewById(R.id.item_img1);
            this.textView1 = (TextView) itemView.findViewById(R.id.item_tv1);
            this.textView2 = (TextView) itemView.findViewById(R.id.item_tv2);
        }
    }

    //加载搜索结果
    public void loadSearch(String content){
        RequestParams params = new RequestParams(API.getSearchUrl(content));
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    data2 = data;
                    state = result.getInt("Status");
                    judgeResult(state);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    //设置recyclerview的item之间的间距
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
//            outRect.bottom = space;
            outRect.top = space;
            // Add top margin only for the first item to avoid double space between items
//            if(parent.getChildPosition(view) == 0)
//                outRect.top = space;
        }

    }

    @Event(R.id.search_result_back)
    private void back(View view){
        super.onBackPressed();
    }


    class SearchItemClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SearchResultActivity.this, FoodGoodsPageActivity.class);
            intent.putExtra("productID", (String[]) v.getTag());
            startActivity(intent);
        }
    }


    @Event(R.id.search_result_fail)
    private void background(View view){
        //关闭软键盘
        InputMethodManager imm = (InputMethodManager) SearchResultActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken() , 0);
    }
}
